package com.szrt.ch04.utils.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DBUtil {
	
	
	
	
	public static String getId(){
		Date date = new Date();
		System.out.println(date);
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		
		String xx  = sdf.format(date);
		
		//System.out.println(xx);
		
		
		double yy = Math.random();
		
		System.out.println((int)(yy*1000000));
		
		
		return xx + (int)(yy*1000000);
	}
	
	/**
	 * 获取mysql数据库连接
	 * @return
	 */
	public static Connection  getConnectionMySQL(){
		Connection connection=null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/tmall", "root", "123456");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		System.out.println(connection);
		return connection;
	}
	
	
	/**
	 * 获取oracle的数据库连接
	 * @return
	 */
	public static Connection  getConnectionOracle(){
		Connection connection=null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			connection = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe", "scott", "123456");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		System.out.println(connection);
		return connection;
	}
	
	
	public static void closeResultSet(ResultSet rs){
		if(null != rs ){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	public static void closePreparedStatement(PreparedStatement ps){
		//关闭预编译语句   
		if(null != ps){
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void closeConnection(Connection connection){
		//关闭预编译语句   
		if(null != connection){
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 关闭结果集合连接
	 * @param rs
	 * @param connection
	 */
	public static void closeResource(ResultSet rs,PreparedStatement ps,Connection connection){
		
		//关闭结果集
		closeResultSet(rs);
		
		
		//关闭预编译语句   
		closePreparedStatement(ps);
		
		//关闭连接
		closeConnection(connection);
	}

}
